package flc.ast.fragment;

import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.WorkTimeSetActivity;
import flc.ast.bean.ClockInBean;
import flc.ast.bean.CycleBean;
import flc.ast.bean.HourWageBean;
import flc.ast.databinding.FragmentClockInBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.Str2NumUtil;
import stark.common.basic.utils.TimeUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ClockInFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ClockInFragment extends BaseNoModelFragment<FragmentClockInBinding> {

    private String goWorkTime, afterWorkTime;
    private boolean goWorkClockIn, afterClockIn;
    private List<ClockInBean> listSp = new ArrayList<>();
    private ClockInBean clockInBean;
    private int todayPos;
    private String format = "%.1f";

    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvTime.setText(TimeUtils.getNowString(new SimpleDateFormat("HH:mm:ss")));
            mDataBinding.tvDate.setText(TimeUtils.getNowString(new SimpleDateFormat("MM月dd日 EEEE")));
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.fragment_clock_in;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.rlClockIn.setOnClickListener(this);
        mDataBinding.llWorkTimeSet.setOnClickListener(this);

        mHandler = new Handler();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.rlClockIn://打卡
                clockIn();
                break;
            case R.id.llWorkTimeSet://工作时间设置
                startActivity(WorkTimeSetActivity.class);
                break;
        }
    }

    @Override
    protected void initData() {

    }

    private void getData() {
        goWorkTime = SPUtil.getString(mContext, Content.goWorkTime, "09:00");
        afterWorkTime = SPUtil.getString(mContext, Content.afterWorkTime, "18:00");
        int late = SPUtil.getInt(mContext, Content.late, 0);
        double duration = Str2NumUtil.parse(SPUtil.getString(mContext, Content.overtimeDuration, "0"), 0);
        mDataBinding.tvLate.setText(String.valueOf(late));
        mDataBinding.tvOvertimeDuration.setText(getString(R.string.hour_num, String.format(format, duration)));

        mDataBinding.tvWorkHour.setText(goWorkTime + "-" + afterWorkTime);
        mDataBinding.tvGoWorkTime.setText(getString(R.string.go_work_text) + goWorkTime);
        mDataBinding.tvAfterWorkTime.setText(getString(R.string.after_work_text) + afterWorkTime);

        listSp.clear();
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy年MM月d日"));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(TimeUtils.getNowDate());
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        List<CycleBean> listCycle = AppSpUtils.getCycleList();
        if (listCycle.get(week - 1).isSelected()) {
            mDataBinding.rlFunction.setVisibility(View.VISIBLE);
            mDataBinding.llClockIn.setVisibility(View.VISIBLE);
            listSp = AppSpUtils.getClockInList();
            if (listSp != null && listSp.size() != 0) {
                if (listSp.get(listSp.size() - 1).getDate().equals(date)) {
                    todayPos = listSp.size() - 1;
                } else {
                    todayPos = listSp.size();
                    listSp.add(new ClockInBean(date, "", ""));
                    AppSpUtils.saveClockInList(listSp);
                }
            } else {
                listSp = new ArrayList<>();
                listSp.add(new ClockInBean(date, "", ""));
                AppSpUtils.saveClockInList(listSp);
            }
            clockInBean = listSp.get(todayPos);
            goWorkClockIn = clockInBean.getGoWork().isEmpty() ? false : true;
            afterClockIn = clockInBean.getAfterWork().isEmpty() ? false : true;

            if (goWorkClockIn && afterClockIn) {
                mDataBinding.ivClockInSuc.setVisibility(View.VISIBLE);
                mDataBinding.rlClockIn.setVisibility(View.GONE);
                mDataBinding.ivGoWorkClockIn.setVisibility(View.VISIBLE);
                mDataBinding.tvGoWorkClockIn.setText(clockInBean.getGoWork() + getString(R.string.clocked_in));
                mDataBinding.tvGoWorkClockIn.setTextColor(Color.parseColor("#5476FC"));
                mDataBinding.ivAfterWorkClockIn.setVisibility(View.VISIBLE);
                mDataBinding.tvAfterWorkClockIn.setText(clockInBean.getAfterWork() + getString(R.string.clocked_in));
                mDataBinding.tvAfterWorkClockIn.setTextColor(Color.parseColor("#5476FC"));
            } else {
                mDataBinding.ivClockInSuc.setVisibility(View.GONE);
                mDataBinding.rlClockIn.setVisibility(View.VISIBLE);
                if (!goWorkClockIn) {
                    mDataBinding.ivClockInImg.setImageResource(R.drawable.sbdk);
                    mDataBinding.tvClockInTime.setText(goWorkTime);
                    mDataBinding.ivGoWorkClockIn.setVisibility(View.GONE);
                    mDataBinding.tvGoWorkClockIn.setText(getString(R.string.no_card));
                    mDataBinding.tvGoWorkClockIn.setTextColor(Color.parseColor("#969696"));
                    mDataBinding.ivAfterWorkClockIn.setVisibility(View.GONE);
                    mDataBinding.tvAfterWorkClockIn.setText(getString(R.string.no_card));
                    mDataBinding.tvAfterWorkClockIn.setTextColor(Color.parseColor("#969696"));
                } else {
                    mDataBinding.ivClockInImg.setImageResource(R.drawable.xbdk);
                    mDataBinding.tvClockInTime.setText(afterWorkTime);
                    mDataBinding.ivGoWorkClockIn.setVisibility(View.VISIBLE);
                    mDataBinding.tvGoWorkClockIn.setText(clockInBean.getGoWork() + getString(R.string.clocked_in));
                    mDataBinding.tvGoWorkClockIn.setTextColor(Color.parseColor("#5476FC"));
                    mDataBinding.ivAfterWorkClockIn.setVisibility(View.GONE);
                    mDataBinding.tvAfterWorkClockIn.setText(getString(R.string.no_card));
                    mDataBinding.tvAfterWorkClockIn.setTextColor(Color.parseColor("#969696"));
                }
            }
        } else {
            mDataBinding.rlFunction.setVisibility(View.GONE);
            mDataBinding.llClockIn.setVisibility(View.GONE);
        }
    }

    private void clockIn() {
        if (goWorkClockIn && afterClockIn) return;
        String time = TimeUtils.getNowString(new SimpleDateFormat("HH:mm"));
        if (!goWorkClockIn) {
            long goWork = TimeUtils.string2Millis(goWorkTime, new SimpleDateFormat("HH:mm"));
            if (TimeUtils.string2Millis(time, new SimpleDateFormat("HH:mm")) > goWork) {
                int late = SPUtil.getInt(mContext, Content.late, 0);
                SPUtil.putInt(mContext, Content.late, late + 1);
            }
            listSp.get(todayPos).setGoWork(time);
        } else {
            long after = TimeUtils.string2Millis(afterWorkTime, new SimpleDateFormat("HH:mm"));
            if (after <= TimeUtils.string2Millis(time, new SimpleDateFormat("HH:mm"))) {
                listSp.get(todayPos).setAfterWork(time);
                double overtime = (TimeUtils.string2Millis(time, new SimpleDateFormat("HH:mm")) - after) / 1000 / 60 / 60;
                double duration = Str2NumUtil.parse(SPUtil.getString(mContext, Content.overtimeDuration, "0"), 0);
                SPUtil.putString(mContext, Content.overtimeDuration, String.valueOf((duration + overtime)));
            } else {
                ToastUtils.showShort(getString(R.string.no_after_work_time));
                return;
            }
        }
        AppSpUtils.saveClockInList(listSp);
        mDataBinding.ivClockInSuc.setVisibility(View.VISIBLE);
        mDataBinding.rlClockIn.setVisibility(View.GONE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getData();
            }
        }, 500);
    }


    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    public void onResume() {
        super.onResume();
        startTime();
        getData();
    }

    @Override
    public void onStop() {
        super.onStop();
        stopTime();
    }
}